package org.jerrymouse.jsa4j.vfs.local;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.jerrymouse.jsa4j.vfs.FileObject;

public class LocalFileObject implements FileObject {
	protected File file;
	private static String UTF8 = "UTF-8";

	public LocalFileObject(String basePath) {
		file = new File(basePath);
	}

	public LocalFileObject(FileObject directory, String name) {
		file = new File(directory.getPath(), name);
	}

	@Override
	public boolean delete() {
		if (file.isDirectory())
			return deleteDirectory(file);
		return file.delete();
	}

	private boolean deleteDirectory(File path) {
		if (path.exists()) {
			File[] files = path.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return (path.delete());
	}

	@Override
	public boolean exists() {
		return file.exists();
	}

	@Override
	public boolean isDirectory() {
		return file.isDirectory();
	}

	@Override
	public FileObject mkDir() {
		file.mkdirs();
		return new LocalDirectory(file.getAbsolutePath());
	}

	@Override
	public String getName() {
		return file.getName();
	}

	@Override
	public String getPath() {
		return file.getAbsolutePath();
	}

	@Override
	public byte[] getContent() {
		return getFile().getContent();
	}

	@Override
	public FileObject write(byte[] content, boolean append) {
		return getFile().write(content, append);
	}

	@Override
	public FileObject write(byte[] content) {
		return getFile().write(content);
	}

	@Override
	public boolean isFile() {
		return file.isFile();
	}

	public LocalFile getFile() {
		return new LocalFile(file.getAbsolutePath());
	}

	@Override
	public List<FileObject> getChildren() {
		if (isDirectory())
			return new LocalDirectory(file.getAbsolutePath()).getChildren();
		return null;
	}

	@Override
	public String getStringContent() {
		try {
			return new String(getContent(), UTF8);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public FileObject write(String content, boolean append) {
		try {
			return write(content.getBytes(UTF8), append);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public FileObject write(String content) {
		try {
			return write(content.getBytes(UTF8));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String toString() {
		return file.toString();
	}
}
